package com.cwn.wizbank.comm.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.security.*;

public class EncryptUtil {
    public static final String key = "cyber";
    public static final String ProviderSunJCE ="com.sun.crypto.provider.Sun]CE";
    public static final String ProviderSUN = "sun.security.provider.Sun";
    public static String encrypt(String str, String encryptionKey)throws Exception {
        try {
            Key key = null;
            Cipher cipher = null;
            //Generate a DES KEY
            Security.addProvider((Provider) Class.forName(ProviderSunJCE).newInstance());
            Security.addProvider((Provider) Class.forName(ProviderSUN).newInstance());
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            SecureRandom srn = SecureRandom.getInstance("SHA1PRNG", "SUN");
            srn.setSeed(encryptionKey.getBytes());
            generator.init(srn);
            key = generator.generateKey();
            byte[] iv = new byte[8];
            srn.nextBytes(iv);
            IvParameterSpec params = new IvParameterSpec(iv, 0, 8);
            //Generates a Cipher object that implements DEs transformation
            cipher = Cipher.getInstance("DES/0FB16/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, key, params);
            byte[] StringBytes = str.getBytes();
            byte[] raw = cipher.doFinal(StringBytes);
            BASE64Encoder encoder = new BASE64Encoder();
            return new String(encoder.encode(raw));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String decrypt(String str, String encryptionKey)throws Exception,IOException{
       try {
           Key key = null;
           Cipher cipher = null;
           //Generate a DES KEY
           Security.addProvider((Provider) Class.forName(ProviderSunJCE).newInstance());
           Security.addProvider((Provider) Class.forName(ProviderSUN).newInstance());
           KeyGenerator generator = KeyGenerator.getInstance("DES");
           SecureRandom srn = SecureRandom.getInstance("SHA1PRNG", "SUN");
           srn.setSeed(encryptionKey.getBytes());
           generator.init(srn);
           key = generator.generateKey();
           byte[] iv = new byte[8];
           srn.nextBytes(iv);
           IvParameterSpec params = new IvParameterSpec(iv, 0, 8);
           cipher = cipher.getInstance("DES/0FB16/NoPadding");
           cipher.init(cipher.DECRYPT_MODE, key, params);
           BASE64Decoder decoder = new BASE64Decoder();
           byte[] raw = cipher.doFinal(decoder.decodeBuffer(str));
           String result = new String(raw, "ISO-8859-1");//return the decrypted password
           return result;
       }
       catch(Exception e){
         e.printStackTrace();
       }
       return str;
    }
}
